// 1. 小数相加
// 2. 大数求和
// 3. 大数求积
// 4. sum 递归求和
// 5. 数字转千分位

function floatAdd(num1, num2) {
    let s1 = num1.toString().split('.')[1].length;
    let s2 = num2.toString().split('.')[1].length;
    let max = Math.max(s1, s2)
    let pow = Math.pow(10, max)
    console.log(s1, s2, max, pow)

    return (num1 * pow + num2 * pow) / pow
}

console.log(floatAdd(1.1, 1.23))


function bigAdd(num1, num2) {
    let s1 = num1.toString().length;
    let s2 = num2.toString().length;
    let max = Math.max(s1, s2);

    let str1 = num1.toString().padStart(max, 0)
    let str2 = num2.toString().padStart(max, 0)

    let res = '';
    let j = 0;
    for (let i = max - 1; i >= 0; i--) {
        let sum = parseInt(str1[i]) + parseInt(str2[i]) + j * 1;
        j = Math.floor(sum / 10);
        res = sum % 10 + res
    }

    return j > 0 ? "1" + res : res
}
console.log(bigAdd(11, 22))


function bigMath(num1, num2) {
    let s1 = num1.toString().length;
    let s2 = num2.toString().length;
    let arr = [];
    for (let i = s1 - 1; i >= 0; i--) {
        for (let j = s2 - 1; j >= 0; j--) {
            let n = i + j;
            let m = i + j + 1;
            let total = num1.toString()[i] * num2.toString()[j] + (arr[m] || 0) * 1;

            arr[n] = Math.floor(total / 10) + (arr[n] || 0)
            arr[m] = total % 10
        }
    }

    console.log(arr, '=====')

    return arr.join('').replace(/^[0]+/, '')
}
console.log(bigMath(11, 22))

function sum(arr) {
    function fn(i){
        return i >= arr.length ? 0 : arr[i] + fn(i+1)
    }
    return fn(0)
}
console.log(sum([1,2,3,4]))

console.log('1234567.89'.replace(/(?=\B(\d{3})+$)/g, ',')) // 不能处理小数
console.log('1234567.89'.replace(/(?=\B(\d{3})+(?!\d))/g, ','))
console.log(1234567.89.toLocaleString())



// 红包分发 包含红包数量 红包金额 最小金额
function genPackets(total, num, min){
  let remaining = total; // 剩余金额
  let res = []; // 红包数组

  for(let i = 0; i< num; i++){
    if(i === num - 1){
      res.push(remaining.toFixed(2))
    } else {
      let max = remaining - (num - (i+1))* min;
      let amount = Math.random() * (max - min) + min;
      amount = amount.toFixed(2)
      remaining = remaining - amount;
      res.push(amount)
    }
  }
   // 打乱红包顺序，使其看起来更随机
  for (let i = res.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [res[i], res[j]] = [res[j], res[i]];
  }
  return res;
}

console.log(genPackets(10, 10, 0.5))